package apobates.gui.formatter.richedit;

import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyleSpansBuilder;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 字符串正则匹配
 */
public final class JsonKeyWordRegexMatch extends StylePaneMatch{
    Pattern PATTERN = Pattern.compile(
            "(?<value>(?<=:\\s?)(\\d+|\"[^\"]*\"|true|false|null))"
                    + "|(?<key>[\\w\\d]+)"
    );
    @Override
    public StyleSpans<Collection<String>> computeHighlighting(String text) {
        // System.out.println("HHLine content:"+text);
        Matcher matcher = PATTERN.matcher(text);
        int lastKwEnd = 0;
        StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
        // List<SpanStyleClassResult> sscr = new ArrayList<>();
        while(matcher.find()) {
            String styleClass =
                    matcher.group("key") != null ? "key" :
                            matcher.group("value") != null ? "string" : "default";
            spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
            // sscr.add(new SpanStyleClassResult(0, "TAB", "def", lastKwEnd, matcher.start(), text.length()));
            String valueStyleClass = "default";
            String matchWord = "x:x";
            if(styleClass.equals("string")){
                matchWord = matcher.group("value");
                valueStyleClass = calcJsonValStyleClass(matchWord);
            } else if(styleClass.equals("key")){
                matchWord = matcher.group("key");
                valueStyleClass = "key";
            }
            spansBuilder.add(Collections.singleton(valueStyleClass), matcher.end() - matcher.start());
            // sscr.add(new SpanStyleClassResult(0, matchWord, valueStyleClass, matcher.start(), matcher.end(), text.length()));

            lastKwEnd = matcher.end();
        }
        if(lastKwEnd < text.length()) {
            spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd);
            // sscr.add(new SpanStyleClassResult(0, "lastVAL", "defClass", lastKwEnd, text.length(), text.length()));
        }
        // sscr.stream().forEach(System.out::println);
        return spansBuilder.create();
    }
}
